package com.vanke.devops.api.advice;

import com.vanke.core.bean.ApiBaseResponse;
import com.vanke.core.exception.VankeBusinessException;
import com.vanke.core.exception.VankeCommonExCodeEnum;
import com.vanke.core.util.RequestIdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

/**
 * @author 陈景阳
 * @since 2018/1/3
 */
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {

    private static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ApiBaseResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        logger.error("缺少请求参数", e);
        return setResponse(VankeCommonExCodeEnum.INVALID_REQUEST_FORMAT.getCode(),"required_parameter_is_not_present");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ApiBaseResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("参数解析失败", e);
        return setResponse(VankeCommonExCodeEnum.INVALID_REQUEST_FORMAT.getCode(),"could_not_read_parameter");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiBaseResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error("参数验证失败", e);
        BindingResult result = e.getBindingResult();
        String message = getMessage(result);
        return setResponse(VankeCommonExCodeEnum.INVALID_REQUEST_FORMAT.getCode(),message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public ApiBaseResponse handleBindException(BindException e) {
        logger.error("参数绑定失败", e);
        String message = getMessage(e);
        return setResponse(VankeCommonExCodeEnum.INVALID_REQUEST_FORMAT.getCode(),message);
    }

    private String getMessage(BindingResult result){
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        return String.format("%s:%s", field, code);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public ApiBaseResponse handleServiceException(ConstraintViolationException e) {
        logger.error("参数验证失败", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();

        ApiBaseResponse response =  new ApiBaseResponse();
        response.setRequestId(RequestIdUtils.getRequestId().toString());
        response.setResponseCode(VankeCommonExCodeEnum.INVALID_REQUEST_FORMAT.getCode());
        response.setResponseMessage(("parameter:" + message));
        return response;
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public ApiBaseResponse handleValidationException(ValidationException e) {
        logger.error("参数验证失败", e);
        return setResponse(VankeCommonExCodeEnum.INVALID_REQUEST_FORMAT.getCode(),"validation_exception");
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ApiBaseResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error("不支持当前请求方法", e);
        return setResponse(VankeCommonExCodeEnum.INVALID_REQUEST_FORMAT.getCode(),"request_method_not_supported");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public ApiBaseResponse handleHttpMediaTypeNotSupportedException(Exception e) {
        logger.error("不支持当前媒体类型", e);
        return setResponse(VankeCommonExCodeEnum.INVALID_REQUEST_FORMAT.getCode(),"content_type_not_supported");
    }

    private ApiBaseResponse setResponse(String code,String message){
        ApiBaseResponse response =  new ApiBaseResponse();
        RequestIdUtils.generateRequestId();
        response.setRequestId(RequestIdUtils.getRequestId().toString());
        response.setResponseCode(code);
        response.setResponseMessage(message);
        return response;
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public ApiBaseResponse handleException(Exception e) {
        logger.error("通用异常", e);

        ApiBaseResponse response =  new ApiBaseResponse();
        response.setRequestId(RequestIdUtils.getRequestId().toString());

        if (e instanceof VankeBusinessException){
            return setResponse(((VankeBusinessException) e).getErrorCode(),((VankeBusinessException) e).getErrorMessage());
        } else{
            // 未知异常
            return setResponse(VankeCommonExCodeEnum.SYS_TOO_BUSY.getCode(),VankeCommonExCodeEnum.SYS_TOO_BUSY.getMessage());
        }
    }
}
